'use client'

import { useState, useRef, useCallback, useEffect } from 'react'
import { supabase } from '@/lib/supabase'

interface ChatInputProps {
  onSendMessage: (content: string, images: File[], files: File[]) => Promise<void>
  disabled?: boolean
  userId?: string
  onMessageSent?: () => void
  isDarkMode?: boolean
}

// 国际化文本配置
const i18n = {
  zh: {
    selectImage: '选择图片',
    takePhoto: '拍照',
    selectFile: '选择文件',
    dropHint: '松开鼠标以上传文件',
    placeholder: '输入消息... (Shift+Enter换行, Enter发送)',
    formatHint: '支持图片、文档等多种格式',
    sending: '发送中...',
    send: '发送'
  },
  en: {
    selectImage: 'Select Image',
    takePhoto: 'Take Photo',
    selectFile: 'Select File',
    dropHint: 'Drop to upload files',
    placeholder: 'Type a message... (Shift+Enter for new line, Enter to send)',
    formatHint: 'Support images, documents and more',
    sending: 'Sending...',
    send: 'Send'
  }
}

export default function ChatInput({ onSendMessage, disabled = false, userId, onMessageSent, isDarkMode = false }: ChatInputProps) {
  const [message, setMessage] = useState('')
  const [selectedImages, setSelectedImages] = useState<File[]>([])
  const [selectedFiles, setSelectedFiles] = useState<File[]>([])
  const [isRecording, setIsRecording] = useState(false)
  const [dragActive, setDragActive] = useState(false)
  const [language, setLanguage] = useState<'zh' | 'en'>('zh')

  const fileInputRef = useRef<HTMLInputElement>(null)
  const imageInputRef = useRef<HTMLInputElement>(null)
  const cameraInputRef = useRef<HTMLInputElement>(null)

  // 检测系统语言
  useEffect(() => {
    const detectLanguage = () => {
      const userLang = navigator.language || (navigator as any).userLanguage
      const isZh = userLang.toLowerCase().startsWith('zh')
      setLanguage(isZh ? 'zh' : 'en')
    }
    detectLanguage()
  }, [])

  const t = i18n[language]

  // 处理发送消息
  const handleSend = useCallback(async () => {
    if ((!message.trim() && selectedImages.length === 0 && selectedFiles.length === 0) || disabled) {
      return
    }

    await onSendMessage(message, selectedImages, selectedFiles)

    // 清空输入
    setMessage('')
    setSelectedImages([])
    setSelectedFiles([])
    
    // 触发消息发送后的回调（用于滚动到底部）
    if (onMessageSent) {
      onMessageSent()
    }
  }, [message, selectedImages, selectedFiles, onSendMessage, disabled, onMessageSent])

  // 处理键盘事件
  const handleKeyPress = useCallback((e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSend()
    }
  }, [handleSend])

  // 处理文件选择
  const handleFileSelect = useCallback((files: FileList | null, type: 'image' | 'file') => {
    if (!files) return

    const fileArray = Array.from(files)
    const validFiles = fileArray.filter(file => {
      if (type === 'image') {
        return file.type.startsWith('image/')
      } else {
        // 支持 txt md html word pdf ppt csv excel
        const supportedTypes = [
          'text/plain', 'text/markdown', 'text/html',
          'application/pdf',
          'application/vnd.ms-powerpoint',
          'application/vnd.openxmlformats-officedocument.presentationml.presentation',
          'text/csv',
          'application/vnd.ms-excel',
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ]
        return supportedTypes.includes(file.type) ||
               file.name.endsWith('.txt') ||
               file.name.endsWith('.md') ||
               file.name.endsWith('.html') ||
               file.name.endsWith('.doc') ||
               file.name.endsWith('.docx') ||
               file.name.endsWith('.pdf') ||
               file.name.endsWith('.ppt') ||
               file.name.endsWith('.pptx') ||
               file.name.endsWith('.csv') ||
               file.name.endsWith('.xlsx') ||
               file.name.endsWith('.xls')
      }
    })

    if (type === 'image') {
      setSelectedImages(prev => [...prev, ...validFiles])
    } else {
      setSelectedFiles(prev => [...prev, ...validFiles])
    }
  }, [])

  // 删除选中的文件
  const removeFile = useCallback((index: number, type: 'image' | 'file') => {
    if (type === 'image') {
      setSelectedImages(prev => prev.filter((_, i) => i !== index))
    } else {
      setSelectedFiles(prev => prev.filter((_, i) => i !== index))
    }
  }, [])

  // 拍照功能（移动端）
  const handleCamera = useCallback(() => {
    if (cameraInputRef.current) {
      cameraInputRef.current.setAttribute('capture', 'environment')
      cameraInputRef.current.click()
    }
  }, [])

  // 拖拽上传
  const handleDrag = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true)
    } else if (e.type === 'dragleave') {
      setDragActive(false)
    }
  }, [])

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setDragActive(false)

    const files = e.dataTransfer.files
    // 自动判断文件类型
    const images = Array.from(files).filter(file => file.type.startsWith('image/'))
    const otherFiles = Array.from(files).filter(file => !file.type.startsWith('image/'))

    if (images.length > 0) {
      setSelectedImages(prev => [...prev, ...images])
    }
    if (otherFiles.length > 0) {
      setSelectedFiles(prev => [...prev, ...otherFiles])
    }
  }, [])

  return (
    <div className="max-w-4xl mx-auto">
      {/* 预览区域 */}
      {(selectedImages.length > 0 || selectedFiles.length > 0) && (
        <div className={`mb-3 p-2 sm:p-3 ${isDarkMode ? 'bg-gray-700' : 'bg-gray-50'} rounded-lg`}>
          <div className="flex flex-wrap gap-2">
            {/* 图片预览 */}
            {selectedImages.map((file, index) => (
              <div key={`img-${index}`} className="relative">
                <img
                  src={URL.createObjectURL(file)}
                  alt={file.name}
                  className="w-12 h-12 sm:w-16 sm:h-16 object-cover rounded-lg"
                />
                <button
                  onClick={() => removeFile(index, 'image')}
                  className="absolute -top-1 -right-1 w-5 h-5 sm:w-6 sm:h-6 bg-red-500 text-white rounded-full text-xs hover:bg-red-600 flex items-center justify-center"
                >
                  ×
                </button>
              </div>
            ))}

            {/* 文件预览 */}
            {selectedFiles.map((file, index) => (
              <div key={`file-${index}`} className={`relative flex items-center p-2 ${isDarkMode ? 'bg-gray-800 border-gray-600' : 'bg-white'} rounded-lg border min-w-0 max-w-[200px] sm:max-w-xs`}>
                <div className="mr-2 flex-shrink-0">
                  <svg className={`w-3 h-3 sm:w-4 sm:h-4 ${isDarkMode ? 'text-gray-400' : 'text-gray-600'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                  </svg>
                </div>
                <div className="flex-1 min-w-0">
                  <p className={`text-xs font-medium ${isDarkMode ? 'text-gray-200' : 'text-gray-900'} truncate`}>
                    {file.name}
                  </p>
                  <p className={`text-xs ${isDarkMode ? 'text-gray-400' : 'text-gray-500'}`}>
                    {(file.size / 1024).toFixed(1)}KB
                  </p>
                </div>
                <button
                  onClick={() => removeFile(index, 'file')}
                  className="ml-1 sm:ml-2 w-3 h-3 sm:w-4 sm:h-4 text-red-500 hover:text-red-600 flex-shrink-0"
                >
                  ×
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 输入区域 */}
      <div
        className={`relative border-2 ${isDarkMode ? 'border-gray-700' : 'border-gray-200'} rounded-2xl ${isDarkMode ? 'focus-within:border-gray-600' : 'focus-within:border-gray-400'} transition-colors ${
          dragActive ? (isDarkMode ? 'border-blue-500 bg-blue-900/20' : 'border-blue-400 bg-blue-50') : ''
        }`}
        onDragEnter={handleDrag}
        onDragLeave={handleDrag}
        onDragOver={handleDrag}
        onDrop={handleDrop}
      >
        {/* 功能按钮区 */}
        <div className={`flex items-center p-2 sm:p-3 border-b ${isDarkMode ? 'border-gray-700' : 'border-gray-100'}`}>
          <button
            onClick={() => imageInputRef.current?.click()}
            disabled={disabled}
            className={`p-1.5 sm:p-2 ${isDarkMode ? 'text-gray-400 hover:text-gray-200 hover:bg-gray-700' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-100'} rounded-lg transition-colors disabled:opacity-50`}
            title={t.selectImage}
          >
            <svg className="w-4 h-4 sm:w-5 sm:h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
          </button>

          <button
            onClick={handleCamera}
            disabled={disabled}
            className={`p-1.5 sm:p-2 ${isDarkMode ? 'text-gray-400 hover:text-gray-200 hover:bg-gray-700' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-100'} rounded-lg transition-colors disabled:opacity-50 ml-1`}
            title={t.takePhoto}
          >
            <svg className="w-4 h-4 sm:w-5 sm:h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
          </button>

          <button
            onClick={() => fileInputRef.current?.click()}
            disabled={disabled}
            className={`p-1.5 sm:p-2 ${isDarkMode ? 'text-gray-400 hover:text-gray-200 hover:bg-gray-700' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-100'} rounded-lg transition-colors disabled:opacity-50 ml-1`}
            title={t.selectFile}
          >
            <svg className="w-4 h-4 sm:w-5 sm:h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
          </button>

          {/* 拖拽提示 */}
          {dragActive && (
            <div className={`ml-2 sm:ml-4 text-xs sm:text-sm ${isDarkMode ? 'text-blue-400' : 'text-blue-600'} truncate`}>
              {t.dropHint}
            </div>
          )}
        </div>

        {/* 文本输入区 */}
        <div className="p-2 sm:p-3">
          <textarea
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder={t.placeholder}
            disabled={disabled}
            className={`w-full resize-none border-none outline-none text-sm ${isDarkMode ? 'bg-transparent text-gray-200 placeholder-gray-500' : 'placeholder-gray-400'} disabled:opacity-50`}
            rows={2}
            style={{ minHeight: '32px', maxHeight: '100px' }}
          />

          {/* 发送按钮 */}
          <div className="flex justify-between items-center mt-2">
            <div className={`text-xs ${isDarkMode ? 'text-gray-500' : 'text-gray-400'}`}>
              {t.formatHint}
            </div>
            <button
              onClick={handleSend}
              disabled={disabled || (!message.trim() && selectedImages.length === 0 && selectedFiles.length === 0)}
              className={`px-3 sm:px-4 py-1.5 sm:py-2 ${isDarkMode ? 'bg-blue-600 hover:bg-blue-700' : 'bg-black hover:bg-gray-800'} text-white rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm`}
            >
              {disabled ? t.sending : t.send}
            </button>
          </div>
        </div>
      </div>

      {/* 隐藏的文件输入 */}
      <input
        ref={imageInputRef}
        type="file"
        accept="image/*"
        multiple
        className="hidden"
        onChange={(e) => handleFileSelect(e.target.files, 'image')}
      />

      <input
        ref={cameraInputRef}
        type="file"
        accept="image/*"
        capture="environment"
        className="hidden"
        onChange={(e) => handleFileSelect(e.target.files, 'image')}
      />

      <input
        ref={fileInputRef}
        type="file"
        multiple
        className="hidden"
        onChange={(e) => handleFileSelect(e.target.files, 'file')}
      />
    </div>
  )
}
